package com.coocaa.ops.admin.v1.upload.util;

import com.coocaa.ops.admin.v1.upload.exception.ApkParseException;
import com.coocaa.ops.admin.v1.upload.model.ApkInfoModel;
import com.coocaa.ops.common.tool.date.DateUtil;
import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import com.coocaa.ops.common.tool.math.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author bijiahao
 * @date : 2019/2/18.
 * @description
 */
@Slf4j
public final class ApkIconHandleUtil {
    private ApkIconHandleUtil() {

    }

    /**
     * 处理APK 图标ICONS
     *
     * @param apkInfo
     * @param apkFilePath
     */
    public static void handleApkIcons(ApkInfoModel apkInfo, String apkFilePath) {
        String iconPath = apkInfo.getIcons();
        //获取图标名称
        String fileName = FileAnalyzerUtil.getOriginFileName(iconPath);
        //获取图标扩展名
        String extName = FileAnalyzerUtil.getFileExtName(fileName);
        String rootDir = DateUtil.getCurrentDateStr("yyyyMMdd");
        try {
            ZipFile zipFile = new ZipFile(new File(apkFilePath));
            Enumeration<?> enumeration = zipFile.entries();
            ZipEntry zipEntry = null;
            while (enumeration.hasMoreElements()) {
                zipEntry = (ZipEntry) enumeration.nextElement();
                if (zipEntry.isDirectory()) {

                } else {
                    if (iconPath.equals(zipEntry.getName()) && zipEntry.getSize() > 0) {
                        InputStream inputStream = zipFile.getInputStream(zipEntry);
                        String newFileName = RandomUtil.getRandomLongStr() + extName;
                        String localFilePath = UploadFilePathUtil.getTempUploadPath(rootDir, newFileName);
                        File iconFile = new File(localFilePath);
                        UploadUtil.write2File(inputStream, iconFile);
                        //上传到FTP服务器
                        String remoteFilePath = UploadFilePathUtil.getRemoteFilePathForImg("apkIcon", rootDir, newFileName);
                        UploadUtil.upload2Ftp(iconFile, remoteFilePath);
                        apkInfo.setIcons(remoteFilePath);

                    }
                }
            }
        } catch (IOException e) {
            String errMsg = "APK icon upload processing: " + ExceptionUtil.getStackTraceAsString(e);
            log.error(errMsg);
            throw new ApkParseException(errMsg);
        }
    }
}
